package com.company.controller;

import com.company.bean.Person;
import com.company.utils.JSonUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Auther Xue
 * @Date 2021/4/25
 * @Version 1.0
 * @Desc
 */

//@ResponseBody写给浏览器，不是跳转到页面
//@ResponseBody
//@Controller
//  @RestController =  @ResponseBody + @Controller

//@RequestMapping("")
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String handle01(@RequestParam("name") String name){
        return "Hello,Spring Boot 2!"+name;
    }
    //正常应该返回一个字符串到视图解析器，而json需要返回的是一个字符串
    //市面上很多第三方jar包可以实现这个功能，Jackson只需要加下面那个注解就行
    //@ResponseBody，将服务器返回对象转换为json对象响应回去
    @ResponseBody
    @RequestMapping("/helloJson")
    public String json1() throws JsonProcessingException {
        //需要一个Jackson对象映射器，就是一个类，使用它可以直接将对象转为json字符串
        ObjectMapper mapper = new ObjectMapper();
        //创建一个对象
        Person p = new Person("张三", 50);
        System.out.println(p);
        //将java对象转换为json字符串
        String str = mapper.writeValueAsString(p);
        System.out.println(str);
        //用了@ResponseBody注解，这里会将str以json格式字符串返回
        return str;
    }

    /**
     *          JSON传时间
     * @return
     * @throws JsonProcessingException
     */
    @ResponseBody
    @RequestMapping("/helloJson2")
    public String json2() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        Date date = new Date();
        return JSonUtil.obj2String(date);
    }

    /**
     *              JSON传List
     * @return
     * @throws JsonProcessingException
     */
    @ResponseBody
    @RequestMapping("/helloJson3")
    public String json3() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        List<Person> list = new ArrayList<Person>();
        Person p1 = new Person("张三1", 11);
        Person p2 = new Person("张三2", 22);
        Person p3 = new Person("张三3", 33);
        Person p4 = new Person("张三4", 44);
        list.add(p1);
        list.add(p2);
        list.add(p3);
        list.add(p4);
        String str = mapper.writeValueAsString(list);
        return str;
    }

}
